
import 'package:cached_network_image/cached_network_image.dart';
import 'package:lottie/lottie.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:valovault_reminder/common/bean/val_user_base_info_model.dart';
import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/ui/val_auto_fit_screen_size.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/views/val_reminder_coin_shop_amount_cell.dart';
import 'package:valovault_reminder/pages/mine/val_my_home_about_page.dart';
import 'package:valovault_reminder/pages/mine/val_my_home_edit_user_page.dart';
import 'package:valovault_reminder/pages/mine/val_my_home_setting_page.dart';
import 'package:valovault_reminder/util/val_screen_size_kit.dart';
import 'package:flutter/material.dart';
import '../../common/ui/val_ui_kit_dialog_impl.dart';
import '../../common/ui/val_loader_toast.dart';
import '../../common/util/val_permission_manager_tool.dart';
import '../../common/util/val_shared_preferences_tool.dart';
import '../../util/val_eventbus_manager.dart';
import '../message/val_audio_player.dart';
import '../message/val_audio_recorder.dart';
import '../message/val_audio_work_mask.dart';
import '../message/val_audio_state_type.dart';
import '../notice/val_reminder_coin_shop_page.dart';

class ValMyHomePage extends StatefulWidget {
  const ValMyHomePage({super.key});

  @override
  State<ValMyHomePage> createState() => _ValMyHomePageState();
}

class _ValMyHomePageState extends ValBaseUIPageState<ValMyHomePage> with TickerProviderStateMixin {
  String userName = 'Sam';
  String userId = 'ID : 1146289';
  int userCoin = 0; //金币数
  String userHeader = '';
  bool disposeState = false;
  String recordDuration = '1s';
  bool customUserHeader = false;

  /// 语音
  OverlayEntry? _overlayEntry;
  ValAudioStateType audioState = ValAudioStateType();
  ValRecordAudioStateType get _recordState => audioState.recordAudioState;
  String recordFilePath = '';
  late final AnimationController _controller;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    disposeState = false;
    isAppBar = false;
    extendBodyBehindAppBar = true;
    _controller = AnimationController(vsync: this);
    ValAudioPlayer().addAnimationStartListener('123', () {
      _controller.repeat(reverse: true);
    });
    ValAudioPlayer().addAnimationStopListener('123', () {
      _controller.reset();
    });
    loadUserInfo();
    requestAccountDetailInfoData();
    requestAccountInfo();

    ValEventbusManager.getInstance().eventBus.on().listen((event) {
      if (event.toString() == "coinCharged") {
        requestAccountInfo();
        return;
      }
    });
  }

  @override
  void dispose() {
    disposeState = true;
    _controller.dispose();
    super.dispose();
  }

  loadUserInfo() {
    if (disposeState) {
      return;
    }

    if (ValAppStateTool().accountInfo != null) {
      setState(() {
        userCoin = ValAppStateTool().accountInfo!.availableCoins;
        userId = ValAppStateTool().accountInfo!.userId;
        userName = ValAppStateTool().accountInfo!.nickname ?? "Sam";
        userHeader = ValAppStateTool().accountInfo!.avatarUrl ?? '';
      });

      readCachedRecordFilePath();
      readUserHeadRecord();
    }
  }

  ///获取账号信息
  void requestAccountInfo() {
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo, {'userId' : ValAppStateTool().userId},
            (data, errorCode, message){
          if (errorCode == 0) {
            ValUserBaseInfoModel user = ValUserBaseInfoModel.fromJson(data);
            ValAppStateTool().accountInfo = user;
            loadUserInfo();
          }
        }, (err) {

        });
  }

  ///cell点击
  void onTapCell(int index) {
    if (index == 0){

    }
    else if (index == 1){

    }
    else if (index == 2){
      jumpToAboutPage();
    }
    else if (index == 3){
      pushToConfigSystemPage();
    }
  }

  ///进入个人信息编辑界面
  void jumpToEditUserInfoPage() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      String birthDate = '1995-01-02';
      String country = '';
      if (ValAppStateTool().accountInfo != null) {
        birthDate = ValAppStateTool().accountInfo!.birthday ?? "1995-01-02";
        country = ValAppStateTool().accountInfo!.country ?? '';
      }
      return ValMyHomeEditUserPage(nickName: userName, birthDate: birthDate, userHeader: userHeader, country: country,);
    }),
    ).then((value) => requestAccountDetailInfoData());
  }

  ///录音文件
  void readCachedRecordFilePath() async {
    recordFilePath = await ValLocalStore.getValue("$userId-recordFilePath", '');
    int duration = await ValLocalStore.getValue("$userId-recordDuration", 1);
    recordDuration = '${duration}s';
    setState(() {});
  }

  void readUserHeadRecord() async {
    String userId = ValAppStateTool().accountInfo?.userId ?? "userId";
    String header = await ValLocalStore.getValue("$userId-userHeader", '');
    customUserHeader = header.isNotEmpty;
    setState(() {});
  }

  /// 语音输入
  Future<void> onTapRecordButton() async {
    await PermissionUtils.audio();
    audioState.updateRecordAudioState(
      ValRecordAudioStateType(recording: true, recordingState: 1, noticeMessage: 'While recording, click Stop Recording.'),
    );
    _showAudioRecord(context);
  }

  /// 语音播放
  void onTapRecordContent() {
    if (recordFilePath.isEmpty) {
      return;
    }
    ValAudioPlayer().play('123', recordFilePath);
  }

  /// 语音删除
  void onTapDeleteRecord() {
    setState(() {
      recordFilePath = '';
    });

    ValLocalStore.saveValue("$userId-recordFilePath", '');
    ValLocalStore.saveValue("$userId-recordDuration", 1);
  }

  void _showAudioRecord(BuildContext context) {

    Permission.microphone.status.then((status) async {
      if (status.isGranted) {
        Permission permission = await PermissionUtils.storageForAndroidAudio();
        permission.status.then((status) {
          if (status.isGranted) {
            _hideAudioRecord(true);
            _overlayEntry = OverlayEntry(builder: (BuildContext context) {
              return ValAudioWorkMask(recordAudioState: _recordState, onTapRecordButton: () {
                _hideAudioRecord(false);
              },);
            });
            Overlay.of(context).insert(_overlayEntry!);
            ValAudioRecorder().addTimerListener(() {
              _hideAudioRecord(false);
            });
            ValAudioPlayer().stop();
          } else {
            ValUIKitDialogImpl.showTowBtn(
              title: 'Authorization required',
              msg: 'If you wish to send voice messages, please first go to Settings to turn on storage or access audio permissions',
              onTapPositive: () {
                ValUIKitDialogImpl.closeDialog();
                PermissionUtils.openSettings();
              },
              btnPositive: 'Go',
            );
          }
        });
      } else {
        ValUIKitDialogImpl.showTowBtn(
          title: 'Authorization required',
          msg: 'The microphone cannot be accessed. If you want to use the microphone, please go to "Settings" to turn on the microphone permission.',
          onTapPositive: () {
            ValUIKitDialogImpl.closeDialog();
            PermissionUtils.openSettings();
          },
          btnPositive: 'Go',
        );
      }
    });
  }

  void _hideAudioRecord(bool isCancel) {
    if (_overlayEntry != null) {
      ValAudioRecorder().stop((path) {
        if (isCancel) return;
        if (ValAudioRecorder().recordDuration > 0) {
          setState(() {
            recordDuration = '${ValAudioRecorder().recordDuration}s';
            ValLocalStore.saveValue("$userId-recordDuration", ValAudioRecorder().recordDuration);
          });
          saveAudioFileData(path);
        } else {
          ValLoaderToast.show('The talking time is too short!');
        }
      });
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  void saveAudioFileData(String path) async {
    setState(() {
      recordFilePath = path;
    });
    ValLocalStore.saveValue("$userId-recordFilePath", recordFilePath);
  }

  void jumpToAboutPage() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return const ValMyHomeAboutPage();
    }),
    );
  }

  void pushToConfigSystemPage() {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return const ValMyHomeSettingPage();
    }),
    );
  }

  void pushToCoinShopPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return const ValReminderCoinShopPage();
      }),
    ).then((value) => requestAccountInfo());
  }

  ///获取账号信息
  void requestAccountDetailInfoData() {
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo, {'userId' : ValAppStateTool().userId},
            (data, errorCode, message){
          if (errorCode == 0) {
            ValUserBaseInfoModel user = ValUserBaseInfoModel.fromJson(data);
            ValAppStateTool().accountInfo = user;
            loadUserInfo();
          }
        }, (err) {

        });
  }

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          child: Container(
              decoration: const BoxDecoration(
                color: Color(0xFF080822),
                image: DecorationImage(
                    image: AssetImage('${ValAssetsName.ASSETS_MINE}val_my_home_ground.png'), fit: BoxFit.fill),
              ),
          ),
        ),
        Positioned(
            top: 32, left: 0, right: 0, height: 218 + 72 + 150,
            child: Column(
              children: [
                //头像
                Container(
                  width: double.infinity,
                  height: 164 + 15,
                  alignment: Alignment.center,
                  child: Stack(
                    children: [
                      Positioned(
                        top:0, left: 0, right: 0, bottom: 15,
                        child: Container(
                          width: 132, height: 132,
                          alignment: Alignment.center,
                          margin: const EdgeInsets.only(top: 32),
                          child: Container(
                            width: 132, height: 132,
                            alignment: Alignment.center,
                            clipBehavior: Clip.hardEdge,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(132),
                            ),
                            // child: userHeader.isEmpty ? Image.asset('${ValAssetsName.ASSETS_MINE}val_my_user_header_holder.png', width: 132, height: 132,) :
                            // Image.network(userHeader, width: 132, height: 132, fit: BoxFit.fill,),
                            child: customUserHeader ? CachedNetworkImage(
                              width: 132,
                              height: 132,
                              fit: BoxFit.fill,
                              imageUrl: userHeader,
                              placeholder: (context, url) =>Image.asset('${ValAssetsName.ASSETS_MINE}val_user_header_default.png', width: 132, height: 132,),
                              errorWidget: (context, url, error) => Image.asset('${ValAssetsName.ASSETS_MINE}val_user_header_default.png', width: 132, height: 132,),
                            ) : Image.asset('${ValAssetsName.ASSETS_MINE}val_user_header_default.png', width: 132, height: 132,),
                          ),
                        ),
                      ),
                      Positioned(
                        bottom:0, left: 0, right: 0, height: 30,
                        child: GestureDetector(
                            onTap: onTapRecordButton,
                            child: Container(
                                margin: const EdgeInsets.only(top: 2),
                                child: Image.asset('${ValAssetsName.ASSETS_MINE}val_my_home_record_icon.png', width: 30, height: 30,)
                            )
                        ),
                      ),
                    ],
                  ),
                ),
                const Padding(padding: EdgeInsets.only(top: 4)),
                //录音
                if (recordFilePath.isNotEmpty)
                  GestureDetector(
                  onTap: onTapRecordContent,
                  child: Container(
                    width: 127, height: 26,
                    padding: const EdgeInsets.only(left: 6, top: 3, bottom: 3, right: 2),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(26.0),
                      gradient: const LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: [Color(0xFFE8A229), Color(0xFFF9C03D), Color(0xFFFCCC41),],
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Lottie.asset(
                              '${ValAssetsName.ASSETS_LOTTIE}im_audio_left.json',
                              controller: _controller,
                              width: 16.w,
                              height: 16.w,
                              onLoaded: (composition){
                                _controller.duration = composition.duration;
                              },
                            ),
                            // Image.asset('${CsConfig.ASSETS_MINE}val_my_home_voice_icon.png', width: 30, height: 30,),
                            Text(recordDuration, style: const TextStyle(fontSize: 12, color: Color(0xFF333333)),),
                          ],
                        ),
                        GestureDetector(
                          onTap: onTapDeleteRecord,
                          child: Image.asset('${ValAssetsName.ASSETS_MINE}val_my_home_delete_icon.png', width: 30, height: 30,),
                        ),
                      ],
                    ),
                  ),
                ),
                if (recordFilePath.isNotEmpty)
                  const Padding(padding: EdgeInsets.only(top: 10)),
                //用户名
                Container(
                  width: double.infinity,
                  height: 30,
                  padding: const EdgeInsets.only(left: 39, right: 39),
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(userName, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 24, color: Colors.white),),
                    ],
                  ),
                ),
                // const Padding(padding: EdgeInsets.only(top: 10)),
                //用户id
                Container(
                  width: double.infinity,
                  height: 20,
                  padding: const EdgeInsets.only(left: 39, right: 39),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('ID:$userId', style: const TextStyle(fontSize: 12, color: Colors.white),),
                    ],
                  ),
                ),
              ],
            )
        ),
        Positioned(
          top: 230, left: 0, right: 0,
          bottom: ValScreenSizeKit.getBottomBarH(context),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              ValReminderCoinShopAmountCell(accountNumber: '$userCoin', onTapCell: pushToCoinShopPage,),
              const Padding(padding: EdgeInsets.only(top: 30)),
              //  菜单
              Center(
                child: Container(
                  // color: Colors.red,
                  alignment: Alignment.center,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 20, right: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        createMyHomeMenuButton('Edit', 'val_my_home_edit_icon.png', jumpToEditUserInfoPage),
                        createMyHomeMenuButton('About', 'val_my_home_about_icon.png', jumpToAboutPage),
                        createMyHomeMenuButton('Setting', 'val_my_home_setting_icon.png', pushToConfigSystemPage),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget createMyHomeMenuButton(String title, String imageName, GestureTapCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Image.asset(
            '${ValAssetsName.ASSETS_MINE}$imageName',
            width: 63, height: 68,
          ),
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Text(title,
              style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500),),
          ),
        ],
      ),
    );
  }
}